package com.infore.airsupervise.ui.activity;

import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.support.v7.widget.PopupMenu;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

import com.beardedhen.androidbootstrap.font.FontAwesome;
import com.bigkoo.pickerview.OptionsPickerView;
import com.bigkoo.pickerview.TimePickerView;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.infore.airsupervise.R;
import com.infore.airsupervise.adapter.RankDataListAdapter;
import com.infore.airsupervise.app.Constants;
import com.infore.airsupervise.app.StatusConst;
import com.infore.airsupervise.bean.AQIRealDataE;
import com.infore.airsupervise.biz.AQIDataRankBiz;
import com.infore.airsupervise.biz.impl.AQIDataRankBizImpl;
import com.infore.airsupervise.http.BaseResponse;
import com.infore.airsupervise.http.OnServerResponseListener;
import com.infore.airsupervise.ui.widget.SwipeRecyclerView;
import com.infore.airsupervise.utils.DateUtil;
import com.infore.airsupervise.utils.JumpUtil;
import com.infore.airsupervise.utils.ToastUtil;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import retrofit2.Call;

/**
 * 历史排名
 *
 * @作者: dingxinlin
 * @创建时间: 2017/3/19 17:21
 */
public class HistorySortActivity
        extends BaseTitleBarActivity
        implements SwipeRecyclerView.OnActionListener,
        TimePickerView.OnTimeSelectListener,
        OptionsPickerView.OnOptionsSelectListener {


    @BindView(R.id.refreshRecyclerView)
    SwipeRecyclerView refreshRecyclerView;
    @BindView(R.id.tv_time)
    EditText tvTime;
    @BindView(R.id.factor)
    TextView tvfactor;

    private TimePickerView timePickerView= null;
    private OptionsPickerView factorPicker = null ;

    private List<AQIRealDataE.RankBean> datas = new ArrayList<>();
    private RankDataListAdapter quickAdapter;
    private boolean[][] showType = new boolean[][] {
            {true, true, true, true, false, false},
            {true, true, true, false, false, false}
    };
    private List<String> factorList = null;

    private boolean isEnd = true ; //
    private String endTime = null ;
    private String dateFormat = null ;

    /**
     * 网络请求参数
     */
    private int factorType = StatusConst.AIR_TYPE_AQI;
    private int  historyType = StatusConst.STATISTIC_DAY;
    private String time;

    private AQIDataRankBiz dataRankBiz;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_history_sort);
        ButterKnife.bind(this);
        dataRankBiz = new AQIDataRankBizImpl();
        initView();
    }


    private void initView() {
        title.setText("AQI历史排名");
        rightMenu.setFontAwesomeIcon(FontAwesome.FA_FILTER);
        //日期显示

        time = DateUtil.updateTime(
                DateUtil.getCurrentDateStr(false), historyType, false);
        tvTime.setText(time);
        tvTime.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {

                if(historyType == StatusConst.STATISTIC_DAY){
                    endTime = DateUtil.updateTime(
                            DateUtil.getCurrentDateStr(false), historyType, false);
                    dateFormat = DateUtil.FORMAT_DATE;
                }else {
                    endTime = DateUtil.updateTime
                            (DateUtil.getCurrentDateStr(DateUtil.FORMAT_DATE_HOUR), StatusConst.STATISTIC_HOUR, false);
                    dateFormat = DateUtil.FORMAT_DATE_HOUR;
                }
                if(DateUtil.compareDate(s.toString(),endTime ,dateFormat)<=0){
                    isEnd = true ;
                }else {
                    isEnd = false ;
                }
            }
        });

        // 适配器
        quickAdapter = new RankDataListAdapter(R.layout.item_station_range, datas, factorType);
        refreshRecyclerView.setActionListener(this);
        refreshRecyclerView.setAdapter(quickAdapter);
        // 首次自动刷新
        setRefreshing();
       // quickAdapter.setEnableLoadMore(false);
    }

    /**
     * 初始化时间选择
     */
    private void initDatePicker(){
        Calendar endSelectedDate = Calendar.getInstance();
        if (historyType == StatusConst.STATISTIC_DAY) {
            endSelectedDate.add(Calendar.DAY_OF_MONTH,-1);
        }else {
            endSelectedDate.add(Calendar.HOUR_OF_DAY ,-1);
        }
        timePickerView = new TimePickerView.Builder(ctx,this)
                .setTitleText("")
                .setLabel("年", "月", "日", "点", "分", "秒")
                .setType(showType[historyType])
                .isCenterLabel(false)
                .setDividerColor(Color.DKGRAY)
                .setContentSize(18)
                .setRangDate(null , endSelectedDate)
                .setDate(endSelectedDate)
                .setDecorView(null)
                .build();
    }

    /**
     * 因子选择器
     */
    private void initFactorPicker(){
        factorList = new ArrayList<>();
        factorList = Arrays.asList(getResources().getStringArray(R.array.airType));
        factorPicker = new OptionsPickerView.Builder(ctx , this)
                .isCenterLabel(false)
                .setTitleText("因子")
                .setDividerColor(Color.DKGRAY)
                .setDecorView(null)
                .build();
        factorPicker.setPicker(factorList);
    }

    /**
     * 获取历史排名数据
     */
    private void getRankData() {
        tvTime.setText(time);
        Call<BaseResponse> call = dataRankBiz.sendHistoryDataRankRequest(time, historyType, factorType,
                new OnServerResponseListener<List<AQIRealDataE.RankBean>>() {
                    @Override
                    public void onSucceed(List<AQIRealDataE.RankBean> result, String desc) {
                        refreshRecyclerView.commonSuccessHandle(true, result.size());
                        quickAdapter.getData().clear();
                        quickAdapter.addData(result);
                        refreshRecyclerView.getRecyclerView().scrollToPosition(0);
                    }

                    @Override
                    public void onFailed(int errorCode, String title, String desc) {
                        refreshRecyclerView.commonFailedHandle(true, errorCode, title, desc);
                    }
                });
        requests.add(call);
    }




    @Override
    public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
        AQIRealDataE.RankBean rankBean = datas.get(position);
        JumpUtil.jumpFromTo(ctx, NewAQIActivity.class, Constants.INTENT_STR_KEY, rankBean.getMn());
    }


    /**
     * 刷新
     */
    private void setRefreshing() {
        refreshRecyclerView.getSwipeLayout().setRefreshing(true);
        refreshRecyclerView.onRefresh();
    }

    @Override
    public void onRefresh() {
        getRankData();
    }

    @Override
    public void onLoadMore() {
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                refreshRecyclerView.getAdapter().loadMoreEnd();
                refreshRecyclerView.getSwipeLayout().setEnabled(true);
            }
        }, 1000);
    }


    @Override
    protected void onRightMenuClick(View view) {
        //天数小时切换菜单
        PopupMenu popupMenu = new PopupMenu(ctx, rightMenu);
        popupMenu.getMenuInflater().inflate(R.menu.history_rank_type_menu, popupMenu.getMenu());
        popupMenu.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
            @Override
            public boolean onMenuItemClick(MenuItem menuItem) {
                switch (menuItem.getItemId()) {
                    case R.id.menu_rank_hour:
                        historyType = StatusConst.STATISTIC_HOUR;
                        time = DateUtil.updateTime(DateUtil.getCurrentDateStr(DateUtil.FORMAT_DATE_HOUR), StatusConst.STATISTIC_HOUR, false);
                        break;
                    case R.id.menu_rank_day:
                        historyType = StatusConst.STATISTIC_DAY;
                        time = DateUtil.updateTime(DateUtil.getCurrentDateStr(false), StatusConst.STATISTIC_DAY, false);
                        break;
                }
                //重置时间选择器
                initDatePicker();

                setRefreshing();
                return true;
            }
        });
        popupMenu.show();
    }


    @OnClick({R.id.iv_before, R.id.tv_time, R.id.iv_after, R.id.factor})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.iv_before:
                time = DateUtil.updateTime(time, historyType, false);
                setRefreshing();
                break;
            case R.id.tv_time:
                if(timePickerView == null){
                    initDatePicker();
                }
                timePickerView.show(view);
                break;
            case R.id.iv_after:
                if(!isEnd) {
                    time = DateUtil.updateTime(time, historyType, true);
                    setRefreshing();
                }else {
                    ToastUtil.showShort(ctx,"不能超过当前日期");
                }
                break;
            case R.id.factor:
                if(factorPicker == null){
                    initFactorPicker();
                }
                factorPicker.show(view);
                break;
        }
    }

    /**
     * 时间选择
     * @param date
     * @param v
     */
    @Override
    public void onTimeSelect(Date date, View v) {
        Calendar selector = Calendar.getInstance();
        Calendar endCalendar = Calendar.getInstance();
        selector.setTime(date);
        if(historyType == StatusConst.STATISTIC_DAY){
            time = DateUtil.getStringByFormat(date,DateUtil.FORMAT_DATE);
        }else {
            endCalendar.add(Calendar.HOUR_OF_DAY ,-1);
            if(endCalendar.compareTo(selector) != 1 ){
                ToastUtil.showShort(ctx,"不能超过当前日期");
                return ;
            }else {
                time = DateUtil.getStringByFormat(date,DateUtil.FORMAT_DATE_HOUR);
            }
        }
        setRefreshing();
    }

    /**
     * 因子选择
     * @param options1
     * @param options2
     * @param options3
     * @param v
     */
    @Override
    public void onOptionsSelect(int options1, int options2, int options3, View v) {
        tvfactor.setText(factorList.get(options1));
        title.setText(factorList.get(options1) + "历史排名");
        factorType = options1;
        quickAdapter.setFactorType(factorType);
        setRefreshing();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if(dataRankBiz != null){
            dataRankBiz = null;
        }
        timePickerView = null;
        factorPicker = null;
    }
}
